local class = require("class")
local super = require("unknown")

---重复使用仓库
local store = reload("store")
local newt, delt = store()

---@class vessellist:unknown @链表
local this = class(super)

---构造函数
function this:ctor()
    super.ctor(self)
    self:clear()
end

---清理函数
function this:clear()
    self._head = nil ---头节点
    self._tail = nil ---尾节点
    self._next = nil ---迭代
    self._size = 0
end

---获取头节点
function this:reder()
    return self._head
end

---节点数量
function this:size()
    return self._size
end

---尾部加入
---@param data any @节点数据
function this:push_back(data)
    local size = self._size
    local node = newt()
    node.data = data
    self._size = size + 1

    if 0 == size then
        self._head = node
        self._tail = node
    else
        self._tail.later = node
        node.front = self._tail
        self._tail = node
    end

    return node
end

---头部删除
function this:pop_front()
    local head = self._head
    if not head then
        return
    end

    local later = head.later
    self._head = later
    if later then
        later.front = nil
    end
    delt(head)
    local size = self._size
    self._size = size - 1
end

---尾部删除
function this:pop_back()
    local tail = self._tail
    if not tail then
        return
    end

    local front = tail.front
    self._tail = front
    if front then
        front.later = nil
    end
    delt(tail)
    local size = self._size
    self._size = size - 1
end

---插入阶段
---@param node any @数据节点
function this:insert(node, data)
    local new = newt()
    new.data = data
    new.front = node
    new.later = node.later
    node.later = new
    if not new.later then
        self._tail = new
    end
    local size = self._size
    self._size = size + 1
end

---删除节点
---@param node any @数据节点
function this:erase(node)
    local size = self._size
    if 1 ~= size then
        if node == self._head then
            local later = node.later
            self._head = later
            later.front = nil
        elseif node == self._tail then
            self._tail = node.front
            node.front.later = nil
        else
            node.front.later = node.later
            node.later.front = node.front
        end
    else
        self._head = nil
        self._tail = nil
    end
    --删除尾部
    delt(node)
    self._size = size - 1
    return node
end

---迭代函数
---@param t vessellist @链表对象
---@param k any|nil    @访问键值
function this.next(t, k)
    if nil == k then
        k = 1
    else
        k = k + 1
        t._next = t._next and t._next.later
    end
    if t._next then
        return k, t._next.data
    else
        return nil, nil
    end
end

---迭代函数
function this:ipairs()
    self._next = self._head
    return this.next, self, nil
end

---迭代函数
function this:pairs()
    return self:ipairs()
end

---@class listNode @节点类
---@field data any @节点数据
---@field front listNode @前驱节点
---@field later listNode @后继节点

return this